﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using NeuralStock.DataAccess;
using NeuralStock.DomainService.Interfaces;
using NeuralStock.Common;

namespace NeuralStock.DomainService.Implementation
{
    public class CompanyService : BaseService, ICompanyService
    {
        private readonly ICompanyQuotationService quotationService;
        private readonly IFinancialReportService financialReportService;

        public CompanyService(ICompanyQuotationService quotationService, IFinancialReportService financialReportService)
        {
            this.quotationService = quotationService;
            this.financialReportService = financialReportService;
        }

        public IEnumerable<Company> GetAll()
        {
            return DbContext.Company;
        }

        public IEnumerable<Company> GetAllWithQuotationAndFinancialData(int financialReportStartYear, int financialReportEndYear, int quotationStartYear, int quotationEndYear)
        {
            var companies = GetAll().ToList();
            List<Company> result = new List<Company>();

            foreach (var company in companies)
            {
                if (quotationService.QuotationsExist(company.Id, quotationStartYear, quotationEndYear)
                    && financialReportService.FinancialReportsExist(company.Id, financialReportStartYear, financialReportEndYear))
                {
                    result.Add(company);
                }
            }
            return result;
        }

        public Company Get(int companyId)
        {
            return DbContext.Company
                .FirstOrDefault(x => x.Id == companyId);
        }

        public Company Get(string name)
        {
            return DbContext.Company.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
        }

        public void Create(string name)
        {
            Company company = new Company();
            company.Name = name;

            DbContext.Company.AddObject(company);
            DbContext.SaveChanges();
        }

        public void Update(string name, decimal? currentNumberOfShares, string sector, decimal? pe, decimal? pbv)
        {
            Company company = Get(name);
            company.CurrentNumberOfShares = currentNumberOfShares;
            company.PE = pe;
            company.PBV = pbv;
            company.Sector = sector;

            DbContext.SaveChanges();
        }
    }
}
